package com.java110.mall.cart.bmo.storeOrder.impl;

import com.java110.dto.data.DatabusDataDto;
import com.java110.dto.shop.ShopConfigDto;
import com.java110.dto.storeOrderWriteoff.StoreOrderWriteoffDto;
import com.java110.intf.cart.*;
import com.java110.intf.chain.IDataBusInnerServiceSMO;
import com.java110.intf.shop.*;
import com.java110.mall.cart.bmo.storeOrder.IUpdateStoreOrderBMO;
import com.java110.mall.cart.bmo.storeOrderCart.IUpdateStoreOrderCartBMO;
import com.java110.mall.cart.storeOrderEngine.StoreOrderShareAcct;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.account.AccountDto;
import com.java110.dto.app.AppDto;
import com.java110.dto.chain.StoreOrderChainDto;
import com.java110.dto.distributionMode.DistributionModeDto;
import com.java110.dto.groupBuy.GroupBuyDto;
import com.java110.dto.groupBuy.GroupBuyProductDto;
import com.java110.dto.housekeeping.HousekeepingServPoolDto;
import com.java110.dto.housekeeping.HousekeepingServPoolUserDto;
import com.java110.dto.product.ProductSpecValueDto;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.shop.ShopSettingDto;
import com.java110.dto.vipUser.ShopVipLevelDto;
import com.java110.dto.vipUser.ShopVipUserDto;
import com.java110.dto.storeOrder.StoreCartDto;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.dto.storeOrder.StoreOrderCartEventDto;
import com.java110.dto.storeOrder.StoreOrderCartFeeDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.acct.IAccountInnerServiceSMO;
import com.java110.intf.acct.ICouponPoolV1InnerServiceSMO;
import com.java110.intf.acct.ICouponUserV1InnerServiceSMO;
import com.java110.intf.chain.IChainCoreInnerServiceSMO;
import com.java110.intf.goods.IDistributionModeInnerServiceSMO;
import com.java110.intf.goods.IGroupBuyInnerServiceSMO;
import com.java110.intf.goods.IGroupBuyProductInnerServiceSMO;
import com.java110.intf.goods.IProductSpecValueInnerServiceSMO;
import com.java110.intf.goods.IShopDistributionModeInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.account.AccountDetailPo;
import com.java110.po.account.AccountPo;
import com.java110.po.groupBuy.GroupBuyPo;
import com.java110.po.housekeeping.HousekeepingServPoolPo;
import com.java110.po.housekeeping.HousekeepingServPoolUserPo;
import com.java110.po.shop.ShopVipUserPo;
import com.java110.po.storeOrder.StoreCartPo;
import com.java110.po.storeOrder.StoreOrderPo;
import com.java110.po.storeOrder.StoreOrderCartPo;
import com.java110.po.storeOrder.StoreOrderCartEventPo;
import com.java110.po.storeOrder.StoreOrderCartFeePo;
import com.java110.po.storeOrder.StoreOrderCartSendPo;
import com.java110.po.storeOrderWriteoff.StoreOrderWriteoffPo;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.lock.DistributedLock;
import com.java110.utils.util.*;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service("updateStoreOrderBMOImpl")
public class UpdateStoreOrderBMOImpl implements IUpdateStoreOrderBMO {

    private static Logger logger = LoggerFactory.getLogger(UpdateStoreOrderBMOImpl.class);
    public static final String CHAIN_SWITCH = "CHAIN_SWITCH";
    public static final String CHAIN_SWITCH_ON = "ON";

    @Autowired
    private IStoreOrderInnerServiceSMO storeOrderInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderLedgerAcctV1InnerServiceSMO storeOrderLedgerAcctV1InnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartInnerServiceSMO storeOrderCartInnerServiceSMOImpl;

    @Autowired
    private IStoreCartInnerServiceSMO storeCartInnerServiceSMOImpl;

    @Autowired
    private IGroupBuyInnerServiceSMO groupBuyInnerServiceSMOImpl;

    @Autowired
    private IGroupBuyProductInnerServiceSMO groupBuyProductInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartFeeInnerServiceSMO storeOrderCartFeeInnerServiceSMOImpl;


    @Autowired
    private IStoreOrderCartEventInnerServiceSMO storeOrderCartEventInnerServiceSMOImpl;

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IAccountInnerServiceSMO accountInnerServiceSMOImpl;

    @Autowired
    private IHousekeepingServPoolInnerServiceSMO housekeepingServPoolInnerServiceSMOImpl;

    @Autowired
    private IHousekeepingServPoolUserInnerServiceSMO housekeepingServPoolUserInnerServiceSMOImpl;
    @Autowired
    private IStoreOrderCartSendInnerServiceSMO storeOrderCartSendInnerServiceSMOImpl;
    @Autowired
    private IShopDistributionModeInnerServiceSMO shopDistributionModeInnerServiceSMOImpl;
    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;
    @Autowired
    private IShopVipUserInnerServiceSMO shopVipUserInnerServiceSMOImpl;
    @Autowired
    private IShopVipLevelInnerServiceSMO shopVipLevelInnerServiceSMOImpl;
    @Autowired
    private IShopSettingInnerServiceSMO shopSettingInnerServiceSMOImpl;
    @Autowired
    private IDistributionModeInnerServiceSMO distributionModeInnerServiceSMOImpl;

    @Autowired
    private ICouponPoolV1InnerServiceSMO couponPoolV1InnerServiceSMOImpl;

    @Autowired
    private ICouponUserV1InnerServiceSMO couponUserV1InnerServiceSMOImpl;

    @Autowired
    private StoreOrderShareAcct storeOrderShareAcct;

    @Autowired
    private IUpdateStoreOrderCartBMO updateStoreOrderCartBMOImpl;

    @Autowired
    private IChainCoreInnerServiceSMO chainCoreInnerServiceSMOImpl;

    @Autowired
    private IDataBusInnerServiceSMO dataBusInnerServiceSMOImpl;

    @Autowired
    private IShopConfigV1InnerServiceSMO shopConfigV1InnerServiceSMOImpl;

    @Autowired
    private IStoreOrderWriteoffV1InnerServiceSMO storeOrderWriteoffV1InnerServiceSMOImpl;



    /**
     * @param storeOrderPo
     * @return 订单服务能够接受的报文
     */
    @Java110Transactional
    public ResponseEntity<String> update(StoreOrderPo storeOrderPo) {



        /**
         * 线上  商品和服务支付完成后，写 store_order_cart_send
         * 接单的时候 刷新 派人及派送时间，状态
         * 服务 指派和抢单都 刷新 派送人及派送时间 状态
         * 派送人员和维修人员 结单时  刷新状态
         *     支付完成后扣个人时间
         *     派送完成后写入到派送人或者维修人的账户中
         */
        StoreOrderDto storeOrderDto = new StoreOrderDto();
        storeOrderDto.setOrderId(storeOrderPo.getOrderId());
        //storeOrderDto.setState(StoreOrderDto.STATE_WAIT_PAY);

        List<StoreOrderDto> storeOrderDtos = storeOrderInnerServiceSMOImpl.queryOnlyStoreOrders(storeOrderDto);

        Assert.listOnlyOne(storeOrderDtos, "当前未找到相应订单");



        //storeOrderPo.setState(StoreOrderDto.STATE_FINISH_PAY);
        storeOrderPo.setState(StoreOrderDto.STATE_WAIT_SEND);

        ShopConfigDto shopConfigDto = new ShopConfigDto();
        shopConfigDto.setShopId(storeOrderDtos.get(0).getShopId());
        List<ShopConfigDto> shopConfigDtos = shopConfigV1InnerServiceSMOImpl.queryShopConfigs(shopConfigDto);
        // 到店核销 状态修改为待备货
        if(!ListUtil.isNull(shopConfigDtos) && ShopConfigDto.SEND_WAY_USER.equals(shopConfigDtos.get(0).getSendWay())){
            storeOrderPo.setState(StoreOrderDto.STATE_WAIT_READY);

            UserDto userDto = new UserDto();
            userDto.setUserId(storeOrderDtos.get(0).getPersonId());
            List<UserDto> userDtoList = userV1InnerServiceSMOImpl.queryUsers(userDto);
            if (ListUtil.isNull(userDtoList)) {
                throw new IllegalArgumentException("用户信息查询失败，请检查用户状态");
            }
            // 保存到店核销
            StoreOrderWriteoffPo storeOrderWriteoffPo = new StoreOrderWriteoffPo();
            storeOrderWriteoffPo.setWoId(GenerateCodeFactory.getGeneratorId("11"));
            storeOrderWriteoffPo.setOrderId(storeOrderDtos.get(0).getOrderId());
            storeOrderWriteoffPo.setState(StoreOrderWriteoffDto.STATE_WAIT);
            storeOrderWriteoffPo.setShopId(storeOrderDtos.get(0).getShopId());
            storeOrderWriteoffPo.setWoNum(GenerateCodeFactory.getTodayWriteOffCode());
            storeOrderWriteoffPo.setLinkNum(CommonUtil.getLastFourDigits(userDtoList.get(0).getTel()));
            storeOrderWriteoffV1InnerServiceSMOImpl.saveStoreOrderWriteoff(storeOrderWriteoffPo);
        }


        int flag = storeOrderInnerServiceSMOImpl.updateStoreOrder(storeOrderPo);
        if (flag < 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }

        StoreOrderCartDto storeOrderCartDto = new StoreOrderCartDto();
        storeOrderCartDto.setOrderId(storeOrderPo.getOrderId());
        //storeOrderCartDto.setState(StoreOrderCartDto.STATE_WAIT_BUY);
        List<StoreOrderCartDto> storeOrderCartDtos = storeOrderCartInnerServiceSMOImpl.queryStoreOrderCarts(storeOrderCartDto);

        if (ListUtil.isNull(storeOrderCartDtos)) {
            throw new IllegalArgumentException("未找到需要购买商品");
        }

        StoreOrderCartPo storeOrderCartPo = new StoreOrderCartPo();
        storeOrderCartPo.setOrderId(storeOrderPo.getOrderId());
        if (StoreOrderCartDto.CART_TYPE_PRODUCT.equals(storeOrderCartDtos.get(0).getCartType())) {
            storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_SEND);
            // 到店核销 状态修改为待备货
            if(!ListUtil.isNull(shopConfigDtos) && ShopConfigDto.SEND_WAY_USER.equals(shopConfigDtos.get(0).getSendWay())){
                storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_READY);
            }
        } else {
            //第二轮支付时改为 待评价
            if (StoreOrderCartDto.STATE_WAIT_SERV_WAIT_PAY.equals(storeOrderCartDtos.get(0).getState())) {
                storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_REPAIR);
            } else {
                storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_SERV_R);
            }
        }
//        if (StringUtil.isEmpty(storeOrderPo.getExtOrderId())) {
//            storeOrderCartPo.setExtCartId(storeOrderPo.getExtOrderId());
//        }
        flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
        if (flag < 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存购物车失败");
        }

        String payPlatform = MappingCache.getValue(MappingConstant.WECHAT_STORE_DOMAIN, "PAY_PLATFORM");

        //处理派单
        doStoreOrderCartSend(storeOrderDtos.get(0), storeOrderCartDtos);

        for (StoreOrderCartDto tmpStoreOrderCartDto : storeOrderCartDtos) {
            StoreOrderCartEventPo storeOrderCartEventPo = new StoreOrderCartEventPo();
            storeOrderCartEventPo.setCartId(tmpStoreOrderCartDto.getCartId());
            storeOrderCartEventPo.setOrderId(tmpStoreOrderCartDto.getOrderId());
            storeOrderCartEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
            storeOrderCartEventPo.setEventObjType("U");
            storeOrderCartEventPo.setEventObjId(storeOrderDtos.get(0).getPersonId());
            storeOrderCartEventPo.setEventMsg("用户支付完成");
            storeOrderCartEventPo.setShopId(tmpStoreOrderCartDto.getShopId());
            storeOrderCartEventPo.setEventType(StoreOrderCartEventDto.EVENT_TYPE_COMMON);
            flag = storeOrderCartEventInnerServiceSMOImpl.saveStoreOrderCartEvent(storeOrderCartEventPo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存购物车事件失败");
            }
            doDealStoreCart(tmpStoreOrderCartDto);
            doDealGroupBuyProduct(tmpStoreOrderCartDto, storeOrderDtos.get(0));

            doDealStoreCartFee(tmpStoreOrderCartDto, storeOrderDtos.get(0));

            //处理工单
            doDealHousekeepingPool(tmpStoreOrderCartDto, storeOrderDtos.get(0));

            //是否直接收货,线下支付直接收货
            receiveStoreOrderCart(storeOrderDtos.get(0), tmpStoreOrderCartDto);

        }

        dataBusInnerServiceSMOImpl.databusData(new DatabusDataDto(DatabusDataDto.BUY_ORDER_NOTIFY,storeOrderPo.getOrderId()));

        // todo  需要将钱冲到现金账户供 商家提现使用
        if ("ON".equals(payPlatform)) {
            chargeMoneyToShopAccount(storeOrderDtos.get(0));
        }


        //默认添加为会员
        ShopVipUserPo shopVipUserPo = saveStringResponseEntity(storeOrderDtos, storeOrderCartDtos);
        //10.0 通知调用链
        notifyChain(storeOrderDtos.get(0), storeOrderCartDtos);

        if (shopVipUserPo == null) { // 由于配置问题 会员没有添加成功
            return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
        }

        try {
            //优惠券赠送
            StoreOrderCartDto tmpStoreOrderCartDto = new StoreOrderCartDto();
            tmpStoreOrderCartDto.setOrderId(storeOrderPo.getOrderId());
            tmpStoreOrderCartDto.setVipId(shopVipUserPo.getVipId());
            tmpStoreOrderCartDto.setShopId(storeOrderCartDtos.get(0).getShopId());
            tmpStoreOrderCartDto.setPayPrice(storeOrderDtos.get(0).getPayPrice());
            storeOrderInnerServiceSMOImpl.saveOrderGoldCount(tmpStoreOrderCartDto);
        } catch (Exception e) {
            logger.error("赠送优惠券失败", e);
        }

        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");


    }

    private void chargeMoneyToShopAccount(StoreOrderDto tmpStoreOrderDto) {

        AccountDto accountDto = new AccountDto();
        accountDto.setObjId(tmpStoreOrderDto.getShopId());
        accountDto.setAcctType(AccountDto.ACCT_TYPE_CASH);
        List<AccountDto> accountDtos = accountInnerServiceSMOImpl.queryAccounts(accountDto);
        if (ListUtil.isNull(accountDtos)) {
            accountDtos = addAccountDto(accountDto, tmpStoreOrderDto);
        }
        AccountDetailPo accountDetailPo = new AccountDetailPo();
        accountDetailPo.setAcctId(accountDtos.get(0).getAcctId());
        accountDetailPo.setObjId(tmpStoreOrderDto.getShopId());
        accountDetailPo.setAmount(tmpStoreOrderDto.getPayPrice());
        accountDetailPo.setRemark("商品出售金额：" + tmpStoreOrderDto.getOrderId());
        accountDetailPo.setObjType(accountDtos.get(0).getObjType());
        accountInnerServiceSMOImpl.prestoreAccount(accountDetailPo);

    }

    private List<AccountDto> addAccountDto(AccountDto accountDto, StoreOrderDto StoreOrderDto) {
        // todo  查询账户名称 这里如果存在业主则业主名称 不是业主 则 填写用户名称，如果用户都没有 则返回空
        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(StoreOrderDto.getShopId());
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);

        Assert.listOnlyOne(shopDtos, "商铺不存在");
        String acctName = shopDtos.get(0).getShopName();

        if (StringUtil.isEmpty(acctName)) {
            return new ArrayList<>();
        }
        //开始锁代码
        String requestId = DistributedLock.getLockUUID();
        String key = this.getClass().getSimpleName() + "AddCountDto" + StoreOrderDto.getShopId();
        try {
            DistributedLock.waitGetDistributedLock(key, requestId);

            AccountPo accountPo = new AccountPo();
            accountPo.setAmount("0");
            accountPo.setAcctId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_acctId));
            accountPo.setObjId(StoreOrderDto.getShopId());
            accountPo.setObjType(AccountDto.OBJ_TYPE_STORE);
            accountPo.setAcctType(AccountDto.ACCT_TYPE_CASH);
            accountPo.setAcctName(acctName);
            accountPo.setPartId(StoreOrderDto.getShopId());
            accountPo.setLink(shopDtos.get(0).getReturnLink());
            accountInnerServiceSMOImpl.saveAccount(accountPo);
            List<AccountDto> accountDtos = accountInnerServiceSMOImpl.queryAccounts(accountDto);
            return accountDtos;
        } finally {
            DistributedLock.releaseDistributedLock(requestId, key);
        }
    }

    /**
     * 通知调用链
     *
     * @param storeOrderDto
     * @param storeOrderCartDtos
     */
    private void notifyChain(StoreOrderDto storeOrderDto, List<StoreOrderCartDto> storeOrderCartDtos) {
        String chainSwitch = MappingCache.getValue(CHAIN_SWITCH);
        if (!CHAIN_SWITCH_ON.equals(chainSwitch)) {
            return;
        }

        StoreOrderChainDto storeOrderChainDto = new StoreOrderChainDto();
        storeOrderChainDto.setStoreOrderDto(storeOrderDto);
        storeOrderChainDto.setStoreOrderCartDtos(storeOrderCartDtos);

        ResultVo resultVo = null;
        try {
            resultVo = chainCoreInnerServiceSMOImpl.notifyChainOrder(storeOrderChainDto);
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }

        if (resultVo.getCode() != ResultVo.CODE_OK) {
            throw new IllegalArgumentException(resultVo.getMsg());
        }
    }

    private void receiveStoreOrderCart(StoreOrderDto storeOrderDto, StoreOrderCartDto storeOrderCartDto) {

        //分账 线上需要 确认收货  默认时间 到期，前台支付时自动分账,
        if (!AppDto.MALL_APP_ID.equals(storeOrderDto.getAppId())) {
            return;
        }

        updateStoreOrderCartBMOImpl.receiveOrderCart(BeanConvertUtil.covertBean(storeOrderCartDto, StoreOrderCartPo.class));

    }

    private void computeStoreOrderLedgerAcct(StoreOrderDto storeOrderDto) {

        //分账 线上需要 确认收货  默认时间 到期，前台支付时自动分账,
        if (!AppDto.MALL_APP_ID.equals(storeOrderDto.getAppId())) {
            return;
        }
        //调用支付接口 分账
        storeOrderShareAcct.shareAcct(storeOrderDto);
    }

    private ShopVipUserPo saveStringResponseEntity(List<StoreOrderDto> storeOrderDtos, List<StoreOrderCartDto> storeOrderCartDtos) {

        if (StringUtil.isEmpty(storeOrderDtos.get(0).getPersonId()) || "-1".equals(storeOrderDtos.get(0).getPersonId())) {
            return null;
        }

        UserDto userDto = new UserDto();
        userDto.setUserId(storeOrderDtos.get(0).getPersonId());
        List<UserDto> userDtoList = userV1InnerServiceSMOImpl.queryUsers(userDto);
        if (ListUtil.isNull(userDtoList)) {
            throw new IllegalArgumentException("用户信息查询失败，请检查用户状态");
        }

        //查询店铺会员是否存在 如果存在 不添加 add by wuxw
        ShopVipUserDto shopVipUserDto = new ShopVipUserDto();
        shopVipUserDto.setShopId(storeOrderCartDtos.get(0).getShopId());
        shopVipUserDto.setVipTel(userDtoList.get(0).getTel());
        List<ShopVipUserDto> shopVipUserDtos = shopVipUserInnerServiceSMOImpl.queryShopVipUsers(shopVipUserDto);
        if (shopVipUserDtos != null && shopVipUserDtos.size() > 0) {
            return BeanConvertUtil.covertBean(shopVipUserDtos.get(0), ShopVipUserPo.class);
        }


        ShopSettingDto shopSettingDto = new ShopSettingDto();
        shopSettingDto.setShopId(storeOrderCartDtos.get(0).getShopId());
        shopSettingDto.setSettingType("1001");
        shopSettingDto.setSettingKey("AUTO_VIP");
        List<ShopSettingDto> shopSettingDtos = shopSettingInnerServiceSMOImpl.queryShopSettings(shopSettingDto);
        if (shopSettingDtos == null || shopSettingDtos.size() < 1) {
            return null;
        }
        if (!"1".equals(shopSettingDtos.get(0).getSettingValue())) {
            return null;
        }
        ShopVipLevelDto shopVipLevelDto = new ShopVipLevelDto();
        shopVipLevelDto.setShopId(storeOrderCartDtos.get(0).getShopId());
        List<ShopVipLevelDto> shopVipLevelDtos = shopVipLevelInnerServiceSMOImpl.queryShopVipLevels(shopVipLevelDto);
        if (shopVipLevelDtos == null || shopVipLevelDtos.size() < 1) {
            return null;
        }
        int indexShopLevel = shopVipLevelDtos.size() - 1;

        ShopVipUserPo shopVipUserPo = new ShopVipUserPo();
        shopVipUserPo.setShopId(storeOrderCartDtos.get(0).getShopId());
        shopVipUserPo.setUserId(userDtoList.get(0).getUserId());
        shopVipUserPo.setShopScope("0");
        shopVipUserPo.setVipId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
        shopVipUserPo.setStoreId(storeOrderCartDtos.get(0).getStoreId());
        shopVipUserPo.setBirthday(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
        shopVipUserPo.setVipName(userDtoList.get(0).getName());

        shopVipUserPo.setSex(userDtoList.get(0).getSex());
        if (StringUtil.isEmpty(shopVipUserPo.getSex())) {
            shopVipUserPo.setSex(ShopVipUserDto.SEX_MAN);
        }
        shopVipUserPo.setVipTel(userDtoList.get(0).getTel());
        shopVipUserPo.setStartTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));
        shopVipUserPo.setEndTime(DateUtil.getLastTime());
        shopVipUserPo.setVipLevel(shopVipLevelDtos.get(indexShopLevel).getVipLevelId());
        int flag = shopVipUserInnerServiceSMOImpl.saveShopVipUser(shopVipUserPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存默认会员失败");
        }
        return shopVipUserPo;
    }

    private void doStoreOrderCartSend(StoreOrderDto tmpStoreOrderDto, List<StoreOrderCartDto> storeOrderCartDtos) {
        if (StoreOrderCartDto.CART_TYPE_SERV.equals(storeOrderCartDtos.get(0).getCartType())) {
            return;
        }
        DistributionModeDto distributionMode = getShopDistributionMode(tmpStoreOrderDto);
        if (distributionMode == null) {
            return;
        }
        BigDecimal fixedFee = new BigDecimal(Double.parseDouble(distributionMode.getFixedFee()));

        StoreOrderCartSendPo storeOrderCartSendPo = new StoreOrderCartSendPo();
        storeOrderCartSendPo.setSendId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
        //由于派单方案发生变化，cartId需要改为orderId.
        storeOrderCartSendPo.setCartId(tmpStoreOrderDto.getOrderId());
        storeOrderCartSendPo.setShopId(storeOrderCartDtos.get(0).getShopId());
        storeOrderCartSendPo.setModeId(distributionMode.getModeId());
        storeOrderCartSendPo.setModeName(distributionMode.getModeName());
        storeOrderCartSendPo.setPrice(fixedFee.doubleValue() + "");
        storeOrderCartSendPo.setState("1001");
        int flag = storeOrderCartSendInnerServiceSMOImpl.saveStoreOrderCartSend(storeOrderCartSendPo);
        if (flag < 1) {
            throw new IllegalArgumentException("添加派单表失败");
        }
    }

    private void myWithholdAccount(StoreOrderDto tmpStoreOrderDto, double amount) {
        UserDto userDto = new UserDto();
        userDto.setUserId(tmpStoreOrderDto.getPersonId());
        List<UserDto> userDtoList = userV1InnerServiceSMOImpl.queryUsers(userDto);
        if (userDtoList == null || userDtoList.size() < 1) {
            throw new IllegalArgumentException("用户信息查询失败，请检查用户状态");
        }
        UserDto userTel = new UserDto();
        userTel.setTel(userDtoList.get(0).getTel());
        List<UserDto> userDtoListTel = userV1InnerServiceSMOImpl.queryUsers(userTel);
        if (userDtoListTel == null || userDtoListTel.size() < 1) {
            throw new IllegalArgumentException("通过用户手机查询失败，请检查用户状态");
        }
        List<String> temObjId = new ArrayList<>();
        for (UserDto user : userDtoListTel) {
            temObjId.add(user.getUserId());
        }
        AccountDto accountDto = new AccountDto();
        accountDto.setObjIds(temObjId.toArray(new String[temObjId.size()]));
        accountDto.setObjType(AccountDto.OBJ_TYPE_PERSON);
        accountDto.setAcctType(AccountDto.ACCT_TYPE_TIME);
        if (DistributionModeDto.FEE_MODE_TYPE_M.equals(MappingCache.getValue(DistributionModeDto.DOMAIN_AMLL, DistributionModeDto.FEE_MODE_TYPE))) {
            accountDto.setObjType(AccountDto.OBJ_TYPE_STORE);
            accountDto.setAcctType(AccountDto.ACCT_TYPE_CASH);
        }
        List<AccountDto> accountDtoList = accountInnerServiceSMOImpl.queryAccounts(accountDto);
        if (accountDtoList == null || accountDtoList.size() < 1) {
            throw new IllegalArgumentException("账户信息查询失败，请检查账户状态");
        }

        AccountDetailPo accountDetailPo = new AccountDetailPo();
        accountDetailPo.setAcctId(accountDtoList.get(0).getAcctId());
        accountDetailPo.setObjId(accountDtoList.get(0).getObjId());
        accountDetailPo.setObjType(accountDtoList.get(0).getAcctType());
        accountDetailPo.setOrderId(tmpStoreOrderDto.getOrderId());
        accountDetailPo.setAmount(amount + "");
        int flag = accountInnerServiceSMOImpl.withholdAccount(accountDetailPo);
        if (flag < 1) {
            throw new IllegalArgumentException("扣款失败");
        }
    }

    private DistributionModeDto getShopDistributionMode(StoreOrderDto tmpStoreOrderDto) {
        DistributionModeDto distributionModeDto = new DistributionModeDto();
        distributionModeDto.setShopId(tmpStoreOrderDto.getShopId());
        List<DistributionModeDto> shopDistributionModeDtos = distributionModeInnerServiceSMOImpl.queryDistributionModes(distributionModeDto);
        if (shopDistributionModeDtos == null || shopDistributionModeDtos.size() < 1) {
            return null;
        }
        return shopDistributionModeDtos.get(0);
    }

    /**
     * 处理家政工单
     *
     * @param tmpStoreOrderCartDto
     * @param storeOrderDto
     */
    private void doDealHousekeepingPool(StoreOrderCartDto tmpStoreOrderCartDto, StoreOrderDto storeOrderDto) {

        if (!StoreOrderCartDto.CART_TYPE_SERV.equals(tmpStoreOrderCartDto.getCartType())) { // 不是服务跳过
            return;
        }
        HousekeepingServPoolDto housekeepingServPoolDto = new HousekeepingServPoolDto();
        housekeepingServPoolDto.setShopId(tmpStoreOrderCartDto.getShopId());
        housekeepingServPoolDto.setCartId(tmpStoreOrderCartDto.getCartId());
        housekeepingServPoolDto.setState(HousekeepingServPoolDto.STATE_PAY);
        List<HousekeepingServPoolDto> housekeepingServPoolDtos = housekeepingServPoolInnerServiceSMOImpl.queryHousekeepingServPools(housekeepingServPoolDto);

        if (housekeepingServPoolDtos == null || housekeepingServPoolDtos.size() < 1) {
            return;
        }
        HousekeepingServPoolPo housekeepingServPoolPo = new HousekeepingServPoolPo();
        housekeepingServPoolPo.setPoolId(housekeepingServPoolDtos.get(0).getPoolId());
        housekeepingServPoolPo.setShopId(tmpStoreOrderCartDto.getShopId());
        housekeepingServPoolPo.setState(HousekeepingServPoolDto.STATE_APPRAISE);
        housekeepingServPoolInnerServiceSMOImpl.updateHousekeepingServPool(housekeepingServPoolPo);

        // 完成支付
        HousekeepingServPoolUserDto housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
        housekeepingServPoolUserDto.setPoolId(housekeepingServPoolDtos.get(0).getPoolId());
        housekeepingServPoolUserDto.setShopId(housekeepingServPoolDtos.get(0).getShopId());
        housekeepingServPoolUserDto.setState(HousekeepingServPoolUserDto.STATE_PAY_FEE);
        List<HousekeepingServPoolUserDto> housekeepingServPoolUserDtos
                = housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsers(housekeepingServPoolUserDto);
        if (housekeepingServPoolUserDtos == null || housekeepingServPoolUserDtos.size() < 1) {
            return;
        }

        // 1.0 关闭自己订单
        HousekeepingServPoolUserPo housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
        housekeepingServPoolUserPo.setRuId(housekeepingServPoolUserDtos.get(0).getRuId());
        housekeepingServPoolUserPo.setEndTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
        housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_FINISH_PAY_FEE);
        housekeepingServPoolUserPo.setContext("支付" + tmpStoreOrderCartDto.getPayPrice() + "元完成");
        housekeepingServPoolUserPo.setShopId(housekeepingServPoolDtos.get(0).getShopId());
        housekeepingServPoolUserInnerServiceSMOImpl.updateHousekeepingServPoolUser(housekeepingServPoolUserPo);

    }

    /**
     * 购物车收费
     *
     * @param tmpStoreOrderCartDto
     * @param storeOrderDto
     */
    private void doDealStoreCartFee(StoreOrderCartDto tmpStoreOrderCartDto, StoreOrderDto storeOrderDto) {

        //将未支付的费用修改为支付完成
        StoreOrderCartFeeDto storeOrderCartFeeDto = new StoreOrderCartFeeDto();
        storeOrderCartFeeDto.setCartId(tmpStoreOrderCartDto.getCartId());
        storeOrderCartFeeDto.setShopId(tmpStoreOrderCartDto.getShopId());
        storeOrderCartFeeDto.setState(StoreOrderCartFeeDto.STATE_W);
        List<StoreOrderCartFeeDto> storeOrderCartFeeDtos = storeOrderCartFeeInnerServiceSMOImpl.queryStoreOrderCartFees(storeOrderCartFeeDto);

        if (storeOrderCartFeeDtos == null || storeOrderCartFeeDtos.size() < 1) {
            return;
        }
        StoreOrderCartFeePo storeOrderCartFeePo = null;
        BigDecimal totalFee = new BigDecimal(0);
        for (StoreOrderCartFeeDto tmpStoreOrderCartFeeDto : storeOrderCartFeeDtos) {
            storeOrderCartFeePo = new StoreOrderCartFeePo();
            storeOrderCartFeePo.setUpdateTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
            storeOrderCartFeePo.setDetailId(tmpStoreOrderCartFeeDto.getDetailId());
            storeOrderCartFeePo.setShopId(tmpStoreOrderCartFeeDto.getShopId());
            storeOrderCartFeePo.setState(StoreOrderCartFeeDto.STATE_C);
            storeOrderCartFeePo.setExtOrderId(storeOrderDto.getExtOrderId());
            totalFee = totalFee.add(new BigDecimal(tmpStoreOrderCartFeeDto.getPayPrice()));
            storeOrderCartFeeInnerServiceSMOImpl.updateStoreOrderCartFee(storeOrderCartFeePo);
        }


    }

    private void doDealGroupBuyProduct(StoreOrderCartDto tmpStoreOrderCartDto, StoreOrderDto storeOrderDto) {

        GroupBuyProductDto groupBuyProductDto = new GroupBuyProductDto();
        groupBuyProductDto.setProductId(tmpStoreOrderCartDto.getProductId());
        groupBuyProductDto.setStoreId(tmpStoreOrderCartDto.getStoreId());
        List<GroupBuyProductDto> groupBuyProductDtos = groupBuyProductInnerServiceSMOImpl.queryGroupBuyProducts(groupBuyProductDto);

        if (groupBuyProductDtos == null || groupBuyProductDtos.size() < 1) {
            return;
        }

        ProductSpecValueDto productSpecValueDto = new ProductSpecValueDto();
        productSpecValueDto.setProductId(tmpStoreOrderCartDto.getProductId());
        productSpecValueDto.setValueId(tmpStoreOrderCartDto.getValueId());
        productSpecValueDto.setStoreId(tmpStoreOrderCartDto.getStoreId());
        List<ProductSpecValueDto> productSpecValueDtos = productSpecValueInnerServiceSMOImpl.queryProductSpecValues(productSpecValueDto);
        if (productSpecValueDtos == null || productSpecValueDtos.size() < 1) {
            throw new IllegalArgumentException("未找到需要购买商品规格");
        }
        GroupBuyPo groupBuyPo = new GroupBuyPo();
        groupBuyPo.setAmount(tmpStoreOrderCartDto.getPayPrice());
        groupBuyPo.setBatchId(groupBuyProductDtos.get(0).getBatchId());
        groupBuyPo.setBuyCount(tmpStoreOrderCartDto.getCartNum());
        groupBuyPo.setBuyId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_buyId));
        groupBuyPo.setGroupId(groupBuyProductDtos.get(0).getGroupId());
        groupBuyPo.setGroupPrice(tmpStoreOrderCartDto.getPayPrice());
        groupBuyPo.setPersionId(tmpStoreOrderCartDto.getPersonId());
        groupBuyPo.setPersionName(storeOrderDto.getPersonName());
        groupBuyPo.setProductId(tmpStoreOrderCartDto.getProductId());
        groupBuyPo.setSpecId(productSpecValueDtos.get(0).getSpecId());
        groupBuyPo.setState(GroupBuyDto.STATE_SUCCESS);
        groupBuyPo.setStoreId(tmpStoreOrderCartDto.getStoreId());

        int flag = groupBuyInnerServiceSMOImpl.saveGroupBuy(groupBuyPo);

        if (flag < 1) {
            throw new IllegalArgumentException("添加拼团失败");
        }

    }

    /**
     * 处理订单 购物车 和  拼团
     *
     * @param tmpStoreOrderCartDto
     */
    private void doDealStoreCart(StoreOrderCartDto tmpStoreOrderCartDto) {
        StoreCartDto storeCartDto = new StoreCartDto();
        storeCartDto.setCartId(tmpStoreOrderCartDto.getExtCartId());
        storeCartDto.setShopId(tmpStoreOrderCartDto.getShopId());
        storeCartDto.setState(StoreCartDto.STATE_NO_BUY);
        List<StoreCartDto> storeCarts = storeCartInnerServiceSMOImpl.queryStoreCarts(storeCartDto);

        if (storeCarts == null || storeCarts.size() < 1) {
            return;
        }

        StoreCartPo storeCartPo = new StoreCartPo();
        storeCartPo.setCartId(tmpStoreOrderCartDto.getExtCartId());
        storeCartPo.setShopId(tmpStoreOrderCartDto.getShopId());
        storeCartPo.setState(StoreCartDto.STATE_FINISH_BUY);
        int flag = storeCartInnerServiceSMOImpl.updateStoreCart(storeCartPo);

        if (flag < 1) {
            throw new IllegalArgumentException("修改购物车失败");
        }

    }

}
